package com.hainingtong.user.shiro.realm;

import com.hainingtong.user.entity.SysAuth;
import com.hainingtong.user.service.UserService;
import com.hainingtong.user.shiro.token.BaseToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.util.StringUtils;

public class BaseRealm extends AuthorizingRealm {
    @Autowired
    @Lazy
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 由于我们每个需要权限的接口都需要使用 jwt 认证，所以权限只需要在 jwtRealm里面赋予就可以了
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        if (!StringUtils.hasText(authenticationToken.getPrincipal().toString())) {
            return null;
        }
        BaseToken token = (BaseToken) authenticationToken;
        //获取用户信息
        String principal = token.getPrincipal();
        SysAuth auth = userService.findAuthByPrincipalAndType(principal, token.getLoginType().name());
        // 没找到数据或者登录类型不一样 就直接返回
        if (auth == null) {
            return null;
        }

        return new SimpleAuthenticationInfo(auth.getPrincipal(), auth.getCredential(), getName());
    }
}
